from fastapi import APIRouter, Request, Form, Depends, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from backend.dependencies import get_db
from backend.models.models import User, FollowUpRecord
from backend.auth import verify_password, get_password_hash

router = APIRouter(prefix="/admin")
templates = None  # 将由main.py提供


def get_current_admin(request: Request, db: Session = Depends(get_db)):
    username = request.cookies.get("user")
    if not username:
        raise HTTPException(status_code=401, detail="未登录")

    user = db.query(User).filter(User.username == username).first()
    if not user or user.role != "admin":
        raise HTTPException(status_code=403, detail="无管理员权限")

    return user


@router.get("/login", response_class=HTMLResponse)
async def admin_login_form(request: Request):
    return templates.TemplateResponse("admin_login.html", {"request": request, "error": None})


@router.post("/login", response_class=HTMLResponse)
async def admin_login_submit(
    request: Request,
    username: str = Form(...),  # 添加用户名参数
    password: str = Form(...),
    db: Session = Depends(get_db)
):
    # 根据用户名和角色查询管理员账户
    admin_user = db.query(User).filter(User.username == username, User.role == "admin").first()
    if admin_user is not None and verify_password(password, admin_user.password_hash):
        response = RedirectResponse(url="/admin/dashboard", status_code=302)
        response.set_cookie("user", admin_user.username, path="/")
        response.set_cookie("role", admin_user.role, path="/")  # 添加角色cookie
        return response
    else:
        return templates.TemplateResponse("admin_login.html", {"request": request, "error": "管理员用户名或密码错误"})


@router.get("/dashboard", response_class=HTMLResponse)
async def admin_dashboard(request: Request, db: Session = Depends(get_db), admin: User = Depends(get_current_admin)):
    users = db.query(User).all()
    records = db.query(FollowUpRecord).order_by(FollowUpRecord.date.desc()).all()
    return templates.TemplateResponse("admin_dashboard.html", {
        "request": request,
        "users": users,
        "records": records,
        "admin": admin.username
    })


@router.post("/add_user")
async def add_user(
    username: str = Form(...),
    password: str = Form(...),
    role: str = Form(...),
    doctor_name: str = Form(None),  # 添加医生名称参数
    db: Session = Depends(get_db),
    admin: User = Depends(get_current_admin)
):
    existing_user = db.query(User).filter(User.username == username).first()
    if existing_user:
        raise HTTPException(status_code=400, detail="用户名已存在")

    # 检查医生名称是否已存在
    if role == "doctor" and doctor_name:
        existing_doctor = db.query(User).filter(User.doctor_name == doctor_name).first()
        if existing_doctor:
            raise HTTPException(status_code=400, detail="医生名称已存在")

    hashed_password = get_password_hash(password)
    new_user = User(
        username=username,
        password_hash=hashed_password,
        role=role,
        doctor_name=doctor_name if role == "doctor" else None  # 只有医生角色才设置doctor_name
    )
    db.add(new_user)
    db.commit()

    return RedirectResponse(url="/admin/dashboard", status_code=302)


@router.post("/delete_user")
async def delete_user(
    user_id: int = Form(...),
    db: Session = Depends(get_db),
    admin: User = Depends(get_current_admin)
):
    # 确保不能删除当前管理员自己
    current_admin_user = db.query(User).filter(User.username == admin.username).first()
    if current_admin_user.id == user_id:
        return templates.TemplateResponse("admin_dashboard.html", {
            "request": Request(scope={}),
            "error": "不能删除当前登录的管理员账户",
            "users": db.query(User).all(),
            "records": db.query(FollowUpRecord).all(),
            "admin": admin
        })

    # 查找要删除的用户
    user_to_delete = db.query(User).filter(User.id == user_id).first()
    if not user_to_delete:
        return templates.TemplateResponse("admin_dashboard.html", {
            "request": Request(scope={}),
            "error": "用户不存在",
            "users": db.query(User).all(),
            "records": db.query(FollowUpRecord).all(),
            "admin": admin
        })

    # 删除用户
    db.delete(user_to_delete)
    db.commit()

    # 重定向回管理员仪表盘
    return RedirectResponse(url="/admin/dashboard", status_code=302)

# 添加删除随访记录的路由
@router.post("/delete_record")
async def delete_record(
    record_id: int = Form(...),
    db: Session = Depends(get_db),
    admin: User = Depends(get_current_admin)
):
    # 查找要删除的记录
    record_to_delete = db.query(FollowUpRecord).filter(FollowUpRecord.id == record_id).first()
    if not record_to_delete:
        return templates.TemplateResponse("admin_dashboard.html", {
            "request": Request(scope={}),
            "error": "随访记录不存在",
            "users": db.query(User).all(),
            "records": db.query(FollowUpRecord).all(),
            "admin": admin
        })

    # 删除记录（级联删除会自动删除相关的诊断和建议记录）
    db.delete(record_to_delete)
    db.commit()

    # 重定向回管理员仪表盘
    return RedirectResponse(url="/admin/dashboard", status_code=302)


@router.get("/logout")
async def admin_logout():
    response = RedirectResponse(url="/admin/login")
    response.delete_cookie("user", path="/")  # 添加 path 参数
    return response